/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-08
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 
 */
import 'package:chat_client/services/contact_service.dart';
import 'package:chat_client/widgets/global_widgets.dart';
import 'package:flutter/material.dart';
import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/models/apply.dart';

class FriendApplicationScreen extends StatefulWidget {
  const FriendApplicationScreen({Key? key}) : super(key: key);

  @override
  FriendApplicationScreenState createState() => FriendApplicationScreenState();
}

class FriendApplicationScreenState extends State<FriendApplicationScreen> {
  final ContactService _contactService = ContactService.instance;
  List _applicationList = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadApplicationList();
  }

  Future<void> _loadApplicationList() async {
    List updatedList = await _contactService.getLocalFriendRequestList();
    if (mounted) {
      setState(() {
        _applicationList = updatedList;
      });
    }
  }

  Future<void> _handleFriendRequest(String senderId) async {
    if (_isLoading) return; // 防止短时间重复点击
    setState(() => _isLoading = true);

    bool success = await _contactService.handleFriendRequest(senderId, true);

    if (mounted) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(success ? '好友申请已接受' : '处理失败，请重试'),
          duration: const Duration(seconds: 2),
        ),
      );
      _loadApplicationList(); // 刷新列表
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('好友申请列表')),
      body: ListView.separated(
        itemCount: _applicationList.length,
        itemBuilder: (context, index) {
          return customListInfo(
            title: _applicationList[index].opponentNikename,
            subtitle: _applicationList[index].isSend
                ? '我： ${_applicationList[index].applyInfo}'
                : _applicationList[index].applyInfo,
            imageUrl: baseUrl + _applicationList[index].opponentAvatarUrl,
            backgroundColor: const Color.fromARGB(255, 198, 198, 197),
            trailing: _applicationList[index].isSend
                ? Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const Icon(Icons.send, size: 16),
                      const SizedBox(width: 4),
                      Text(_getStatusText(_applicationList[index].status)),
                    ],
                  )
                : _applicationList[index].status == 0
                    ? ElevatedButton(
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(
                                const Color.fromARGB(255, 160, 159, 157))),
                        onPressed: _isLoading
                            ? null
                            : () => _handleFriendRequest(
                                _applicationList[index].opponentId),
                        child: _isLoading
                            ? const SizedBox(
                                width: 16,
                                height: 16,
                                child:
                                    CircularProgressIndicator(strokeWidth: 2),
                              )
                            : const Text('接受'),
                      )
                    : Text(_getStatusText(_applicationList[index].status)),
          );
        },
        separatorBuilder: (context, index) {
          return index == 3
              ? const DividerWithText(text: '我的联系人')
              : buildDivider();
        },
      ),
    );
  }

  String _getStatusText(int status) {
    return ApplyStatusExtension.fromInt(status).label;
  }
}
